/** 导出excel */
export function exportExcel (fileName, tableData) {
  const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' }// 这里的数据是用来定义导出的格式类型
  // const wopts = { bookType: 'csv', bookSST: false, type: 'binary' };//ods格式
  // const wopts = { bookType: 'ods', bookSST: false, type: 'binary' };//ods格式
  // const wopts = { bookType: 'xlsb', bookSST: false, type: 'binary' };//xlsb格式
  // const wopts = { bookType: 'fods', bookSST: false, type: 'binary' };//fods格式
  // const wopts = { bookType: 'biff2', bookSST: false, type: 'binary' };//xls格式
  const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }
  console.log(this, window)
  wb.Sheets['Sheet1'] = window.XLSX.utils.json_to_sheet(tableData)// 通过json_to_sheet转成单页(Sheet)数据
  window.saveAs(new Blob([s2ab(window.XLSX.write(wb, wopts))], { type: 'application/octet-stream' }), fileName + '.' + (wopts.bookType === 'biff2' ? 'xls' : wopts.bookType))
}

export function s2ab (s) {
  if (typeof ArrayBuffer !== 'undefined') {
    let buf = new ArrayBuffer(s.length)
    let view = new Uint8Array(buf)
    for (let i = 0; i < s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
    return buf
  } else {
    let buf = new Array(s.length)
    for (let i = 0; i < s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF
    return buf
  }
}

export function importExcel (obj, fileName, setResults) {
  let rABS = false // 是否将文件读取为二进制字符串
  if (!obj.files) { return }
  let f = obj.files[0]
  {
    let reader = new FileReader()
    // let name = f.name
    reader.onload = function (e) {
      let data = e.target.result
      let wb
      if (rABS) {
        wb = window.XLSX.read(data, { type: 'binary' })
      } else {
        let arr = fixdata(data)
        wb = window.XLSX.read(btoa(arr), { type: 'base64' })
      }
      console.log('wb.SheetNames:', wb.SheetNames)
      let len = wb.SheetNames.length
      let results = []
      for (let i = 0; i < len; i++) {
        results[i] = JSON.stringify(window.XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[i]]))
      }
      setResults(results)
    }
    if (rABS) reader.readAsBinaryString(f)
    else reader.readAsArrayBuffer(f)
  }
}

export function fixdata (data) {
  let o = ''
  let l = 0
  let w = 10240
  for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
  o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
  return o
}
